package com.ruoyi.carUser.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.uuid.UUID;
import com.ruoyi.system.api.utils.QRCodeUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.poi.util.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

/*文件上传类，以及生成二维码并上传至服务器*/
@RestController
@RequestMapping("/file")
public class FileUploadController {
       @RequestMapping("/upload")
    @CrossOrigin
    public String upload(MultipartFile file) throws IOException {
        //https://polaris-image.oss-cn-wuhan-lr.aliyuncs.com/cat1.jpg
        //endPoint: oss-cn-wuhan-lr.aliyuncs.com 地域:北京
        String endPoint = "oss-cn-zhangjiakou.aliyuncs.com";
        //用户信息
        String accessKeyId = "LTAI5tHDuexVE7v6ifrtVvp1";
        String accessKeySecret = "5Iy2pRsaKWRdpykg7yyfwayPzzyqFk";
        //存储空间名称
        String bucketName = "night-folder-file";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        // 上传文件流。
        InputStream inputStream = file.getInputStream();
        //文件原名
        String fileName = file.getOriginalFilename();
        //生成随机文件名
        fileName = UUID.randomUUID().toString().replace("-", "") + fileName;
        //上传文件流
        ossClient.putObject(bucketName, fileName, inputStream);
        //关闭OSSClient。
        ossClient.shutdown();
        //返回文件路径
        // String url = "https://" + bucketName + "." + endPoint + "/img/2024/" + fileName;
        String url = "https://" + bucketName + "." + endPoint + "/" + fileName;
        return url;
    }


    // 将本地的二维码图片上传至服务器，然后删除本地图片(返回值为[核销码，服务器图片路径])
    @RequestMapping("/generateCode")
    public R code(HttpServletResponse response, Long id) throws IOException {
        Map<String,String> map = new HashMap<>();
        map = FileUploadController.generateVerification(id, response);
        //     获取本地图片
        String imgPath = map.get("codePath");
        File file = new File(imgPath);
        //将图片上传至服务器
        FileUploadController fileUploadController = new FileUploadController();
        //服务器图片路径
        String url = "";
        //判断file是否存在
        if (file.exists()) {
            //将file转为MultiPartFile
            MultipartFile multipartFile = FileUploadController.getMultipartFile(file);
            //上传服务器
            url = fileUploadController.upload(multipartFile);
            //删除本地图片
            Files.deleteIfExists(Paths.get(imgPath));
            //修改map集合
            map.put("codePath", url);
        }
        System.out.println(map);
        return R.ok(map);
    }

   /* @PostMapping("upload")
    public R<SysFile> upload(MultipartFile file)
    {
        try
        {
            // 上传并返回访问地址
            String url = sysFileService.uploadFile(file);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            return R.ok(sysFile);
        }
        catch (Exception e)
        {
            log.error("上传文件失败", e);
            return R.fail(e.getMessage());
        }
    }*/

    //生成核销码并根据核销码生成二维码并上传至本地,返回本地图片路径和核销码
    public static Map<String,String> generateVerification(Long id, HttpServletResponse response) {
        Map<String,String> map = new HashMap<>();

        UUID uuid = UUID.randomUUID();
        String destPath = "D:\\ruoyi\\uploadPath\\upload\\" + uuid + ".png";
        //根据订单id生成核销码
        String code = FileUploadController.generateCode(id);
        map.put("code",code);
        try {
            // System.out.println(url);
            //使用工具类生成二维码
            // QRCodeUtil.encode(url, stream);
            QRCodeUtil.encode(code,null,destPath,true);
            // System.out.println(stream);
        } catch (Exception e) {
            e.getStackTrace();
        }
        map.put("codePath",destPath);
        return map;

    }

    //根据订单id生成核销码
    public static String generateCode(Long id){
        StringBuilder code = new StringBuilder();
        Random random = new Random();
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        for (int i = 0; i < 6; i++) {
            int index = random.nextInt(characters.length());
            code.append(characters.charAt(index));
        }
        return id.toString() + code;
    }

    //将File转成MultipartFile
    public static MultipartFile getMultipartFile(File file) {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName());
        try (InputStream input = new FileInputStream(file);
             OutputStream os = item.getOutputStream()) {
            // 流转移
            IOUtils.copy(input, os);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid file: " + e, e);
        }

        return new CommonsMultipartFile(item);
    }

}
